// swagger在线网站：https://editor.swagger.io/#

const swaggerJSDoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");
const path = require("path");

const swaggerInit = (app) => {
  const options = {
    // swagger: "3.0",
    definition: {
      openapi: "3.0.3",
      info: {
        title: "PeakBlog Node Swagger API",
        version: "1.0.0",
        description: "个人博客接口文档(前台和后台)",
        contact: {
          name: "Peak",
          url: "",
          email: "XXX@163.com",
        },
        // version: "1.0.11",
        // termsOfService: "http://swagger.io/terms/",
        // license: {
        //   name: "Apache 2.0",
        //   url: "http://www.apache.org/licenses/LICENSE-2.0.html",
        // },
      },
      externalDocs: {
        description: "后端源码",
        url: "https://github.com/Iontheroad/PeakBlogServer",
      },
      servers: [
        {
          url: "http://localhost:10003/api",
        },
      ],
      tags: [
        {
          name: "article",
          description: "文章相关接口（文章增删改查）、文章评论...",
          externalDocs: {
            description: "Find out more",
            // url: "http://swagger.io",
          },
        },
      ],
      components: {
        securitySchemes: {
          Authorization: {
            type: "http",
            scheme: "bearer",
            bearerFormat: "JWT",
          },
        },
      },
    },
    // 重点，指定 swagger-jsdoc 去哪个路由下收集 swagger 注释
    apis: [path.join(process.cwd(), "/router/*.js"), path.join(process.cwd(), "/router/**/*.js")],
  };
  const swaggerSpec = swaggerJSDoc(options);
  // 可以访问 xxx/swagger.json 看到生成的swaggerJSDoc
  app.get("/swagger.json", function (req, res) {
    res.setHeader("Content-Type", "application/json");
    res.send(swaggerSpec);
  });

  // 可以访问 xxx/api-docs 看到生成的swagger接口文档
  app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));
};

module.exports = swaggerInit;
